﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyVoteMVC.Data;
using MyVoteMVC.Domain;
using MyVoteMVC.Common;
using MyVoteMVC.Common.Objects;
using MyVoteMVC.Data.Repositories;
 
namespace MyVoteMVC.Service
{
    public class VoteUserService : IUserService
    {  
        private const string EmailAddress = "@gzdi.com";//接收方邮箱
        //邮箱需要验证的情况下使用
        private string DesignEmailAddress = "mailtest@gzdi.com";//发送邮箱地址
        private string DesignEmailPassWord = "mail@gzdi";//发送邮箱密码
        //连接发送邮箱服务器使用
        private string EmailHost = "mail.gzdi.com";//发送邮箱服务器
        private const int EmailPort = 25;//发送邮箱端口

        IUnitOfWork unitOfWork;
        IRepository<VT_Users> usersRepository;
        IRepository<VT_Dictionaries> dictionariesRepository;

        public VoteUserService()
        {
            unitOfWork = Factory.GetInstance<IUnitOfWork>();
            usersRepository = unitOfWork.GetRepository<VT_Users>();
            dictionariesRepository = unitOfWork.GetRepository<VT_Dictionaries>();

            VT_Dictionaries v_Dictionaries = dictionariesRepository.GetMany(o => o.Dictionary_Name == "邮件主机" && o.Dictionary_Type == "邮件设置").FirstOrDefault();
            if (v_Dictionaries != null) EmailHost = v_Dictionaries.Dictionary_Value;

            v_Dictionaries = dictionariesRepository.GetMany(o => o.Dictionary_Name == "发送邮件的地址" && o.Dictionary_Type == "邮件设置").FirstOrDefault();
            if (v_Dictionaries != null) DesignEmailAddress = v_Dictionaries.Dictionary_Value;
            
            v_Dictionaries = dictionariesRepository.GetMany(o => o.Dictionary_Name == "发送邮件的密码" && o.Dictionary_Type == "邮件设置").FirstOrDefault();
            if (v_Dictionaries != null) DesignEmailPassWord = v_Dictionaries.Dictionary_Value;

        }
        #region IUserService Members
        //登录
        public VT_Users UserLogin(string userEmailName, string password)
        {
            userEmailName = userEmailName + EmailAddress;
            VT_Users user = usersRepository.GetMany(o => o.User_Email == userEmailName && o.User_Password == password).FirstOrDefault();
            if (user != null) return user;
            else return null;
            //int i = usersRepository.GetMany(o => o.User_Email == userEmailName && o.User_Password == password).Count();
            //if (i > 0) return true;
            //return false;     
        }
        

        //注册 1表示注册成功，2表示已经注册过 -1 表示发邮件出错
        public int Register(string userEmailName, string userName, string realName, out VT_Users user)
        {
            user = null;
            //是否已经注册 2表示已经注册 -1报错
            userEmailName = userEmailName + EmailAddress;
            int i = usersRepository.GetMany(o => o.User_Email == userEmailName).Count();
            if (i > 0) return 2;

            //产生六位随机密码 
            Random rnd = new Random();
            int rndNum = rnd.Next(100000, 999999);

            //加入新纪录 
            user = new VT_Users();
            user.User_Email = userEmailName;
            user.User_ID = Guid.NewGuid().ToString();
            user.User_IfAdmin = 0;
            user.User_Name = userName;
            user.User_Password = rndNum.ToString();
            user.User_RealName = realName;
            user.Created_Date = DateTime.Now;
            unitOfWork.BeginTransaction();
            usersRepository.Add(user);  
         
            //发送邮件
            MailMessage mail = new MailMessage();
            mail.Subject = "投票网站注册";
            mail.From = DesignEmailAddress;
            mail.AddTo(userEmailName);
            mail.Body = "你已经成功注册，用户名是" + userName + ",初始密码是" + rndNum.ToString() + ",请登录后修改，谢谢!";
           
            ESmtpClient eSmtp = new ESmtpClient();
            try
            {
                eSmtp.Host = EmailHost;
                eSmtp.Port = EmailPort;
                eSmtp.EnableAuth = true;//有些邮箱服务器需要进行用户验证，这里需要外部进行配置
                eSmtp.Name = DesignEmailAddress;
                eSmtp.Password = DesignEmailPassWord;
                eSmtp.SendMail(mail);
            }
            catch (SendSmtpException ex)
            {
                unitOfWork.Rollback();
                return -1;
                //throw ex;
            }
            catch (Exception ex)
            {
                unitOfWork.Rollback();
                return -1;
                //throw ex;
            }
            unitOfWork.CommitTransaction();
            return 1; //成功注册
        }
        //忘记密码
        public bool ForgotPassword(string userEmailName)
        {
            //产生六位随机密码 
            Random rnd = new Random();
            int rndNum = rnd.Next(100000, 999999);

            ChangePassword(userEmailName, rndNum.ToString());//少了修改数据库部分

            //发送邮件
            MailMessage mail = new MailMessage();
            mail.Subject = "投票网站修改密码";
            mail.From = DesignEmailAddress;
            mail.AddTo(userEmailName + EmailAddress);
            //mail.AddTo("jiemingyoung@126.com");
            mail.Body = "你已经成功生成新密码，用户名是" + userEmailName + ",随机密码是" + rndNum.ToString() + ",请登录后修改，谢谢!";
           
            ESmtpClient eSmtp = new ESmtpClient();
            try
            {
                eSmtp.Host = EmailHost;
                eSmtp.Port = EmailPort;
                eSmtp.EnableAuth = true;
                eSmtp.Name = DesignEmailAddress;
                eSmtp.Password = DesignEmailPassWord;
                eSmtp.SendMail(mail);
            }
            catch (SendSmtpException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return true;
        }
        //修改密码
        public bool ChangePassword(string userEmailName, string oldPassword, string newPassword)
        { 
            //userName = userName + "@gzdi.com";
            //List<VT_Users> list = activitiesRepository.GetMany(o => o.User_Email == userName).ToList();
            //foreach (var activity in list)
            //{
            //    unitOfWork.BeginTransaction();
            //    activity.User_Password = newPassword;
            //    activitiesRepository.Update(activity);
            //    unitOfWork.CommitTransaction();
            //    return true;
            //}
            //return false;
            userEmailName = userEmailName + EmailAddress;
            VT_Users user = usersRepository.GetMany(o => o.User_Email == userEmailName && o.User_Password == oldPassword).FirstOrDefault();
            if (user != null)
            {
                unitOfWork.BeginTransaction();
                user.User_Password = newPassword;
                usersRepository.Update(user);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;
            
        }

        private bool ChangePassword(string userEmailName, string newPassword)
        {
            //userName = userName + "@gzdi.com";
            //List<VT_Users> list = activitiesRepository.GetMany(o => o.User_Email == userName).ToList();
            //foreach (var activity in list)
            //{
            //    unitOfWork.BeginTransaction();
            //    activity.User_Password = newPassword;
            //    activitiesRepository.Update(activity);
            //    unitOfWork.CommitTransaction();
            //    return true;
            //}
            //return false;
            userEmailName = userEmailName + EmailAddress;
            VT_Users user = usersRepository.GetMany(o => o.User_Email == userEmailName).FirstOrDefault();
            if (user != null)
            {
                unitOfWork.BeginTransaction();
                user.User_Password = newPassword;
                usersRepository.Update(user);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;

        }

        public bool CheckLeader(string userID)
        {
            VT_Users user = usersRepository.GetEntityById(userID);
            if (user != null)
            {
                if (user.User_IfLeaderValue.HasValue)
                {
                    if (user.User_IfLeaderValue.Value == 1)
                        return true;
                }
            }
            return false;
        }

        public bool CheckAdmin(string userID)
        {
            VT_Users user = usersRepository.GetEntityById(userID);
            if (user != null)
            {
                if (user.User_IfAdminValue.HasValue)
                {
                    if (user.User_IfAdminValue.Value == 1)
                        return true;
                }
            }
            return false;
        }
        #endregion
       
        #region IDisposable Members

        private bool m_disposed;
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                if (disposing)
                {
                    unitOfWork.Dispose();   
                }

                // Release unmanaged resources

                m_disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~VoteUserService()
        {
            Dispose(false);
        }
        #endregion
    }
}
